<template>
  <a-modal centered :width="1100" :visible="visible" @cancel="afterClose" :destroyOnClose="true" :footer="null">
    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-card size="small" :bordered="false" title="设置">
              <a-form :form="form" :labelAlign="'left'">
                <a-form-item v-bind="formItemLayout" :label="label1">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selResValue1" @change="changesubTypeMain">
                    <a-select-option v-for="(item, index) in selRes1" :key="item.name" :value="item.index">{{ item.name }}</a-select-option>
                  </a-select>
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="resolutionValue1" @change="changeResolution1">
                    <a-select-option v-for="(item, index) in resolution1" :key="item.name" :value="item.index">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" :label="label2">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selResValue2" @change="changeSelRes2">
                    <a-select-option v-for="(item, index) in selRes2" :key="item.name" :value="item.index">{{ item.name }}</a-select-option>
                  </a-select>
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="resolutionValue2" @change="changeResolution2">
                    <a-select-option v-for="(item, index) in resolution2" :key="item.name" :value="item.index">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item v-bind="formItemLayout" label="扫描尺寸">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selScanSizeValue" @change="changescansize">
                    <a-select-option v-for="(item, index) in selScanSize" :key="item.name" :value="item.index">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
                <!-- <a-form-item v-bind="formItemLayout" label="旋转角度">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selRotateValue" @change="changerotate">
                    <a-select-option v-for="(item, index) in selRotate" :key="item.name" :value="item.index">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>-->
                <a-form-item v-bind="formItemLayout" label="纠偏裁边" style="text-align:center">
                  <a-checkbox :checked="rotatecrop" @change="RotateCrop"></a-checkbox>
                </a-form-item>
                <a-form-item style="text-align:center">
                  <a-button type="primary" @click="Left">左转</a-button>
                  <a-button type="primary" @click="Right" style="margin-left:10px">右转</a-button>
                </a-form-item>
                <!-- <a-form-item v-bind="formItemLayout" label="颜色">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selColorValue" @change="changecolor">
                    <a-select-option v-for="(item, index) in selColor" :key="item.name" :value="item.index">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>-->
                <!-- <a-form-item v-bind="formItemLayout" label="设备列表">
                  <a-select showSearch optionFilterProp="children" :filterOption="filterOption" v-model="selDevValue" @change="changedev">
                    <a-select-option v-for="(item, index) in selDev" :key="item.name" :value="item.index">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>-->
                <!-- <a-form-item v-bind="formItemLayout" label="去底色" style="text-align:center">
                  <a-checkbox :checked="delbkcolor" @change="RemoveBackColor"></a-checkbox>
                </a-form-item>-->
              </a-form>
            </a-card>
          </a-col>
          <a-col :md="18" :sm="24">
            <a-card size="small" :bordered="false" title="预览">
              <a-row>
                <a-col :md="12" :sm="24">
                  <a-card size="small" :bordered="false" title="主头">
                    <object id="view1" type="application/x-eloamplugin" height="300" name="view"></object>
                  </a-card>
                </a-col>
                <a-col :md="12" :sm="24">
                  <a-card size="small" :bordered="false" title="副头">
                    <object id="view2" type="application/x-eloamplugin" height="300" name="view"></object>
                  </a-card>
                </a-col>
              </a-row>
              <!-- <div>
                <object classid="clsid:090457CB-DF21-41EB-84BB-39AAFC9E271A" id="ScanCtrl" codebase="*.cab#version=1,0,0,1" width="660" height="400"></object>
              </div>-->
            </a-card>
            <a-row :gutter="24">
              <a-button type="primary" @click="OpenVideo">开始预览</a-button>
              <a-button type="primary" @click="CloseVideo" style="margin-left:10px">停止预览</a-button>
              <a-button type="danger" @click="TakePic" style="margin-left:10px">拍照</a-button>
              <a-button type="primary" @click="Property" style="margin-left:10px">属性</a-button>
              <!-- <a-button type="primary" @click="ZoomIn" style="margin-left:10px">放大</a-button>
              <a-button type="primary" @click="ZoomOut" style="margin-left:10px">缩小</a-button>-->
            </a-row>
            <!-- <a-card size="small" :bordered="false" title="文件列表">
              <div>
                <object id="EThumbnails" classid="CLSID:E8B3DD46-A440-4C3C-AB0A-DC689EEBDA84" width="660" height="150"></object>
              </div>
            </a-card>-->
            <!-- <a-row :gutter="24">
              <a-button type="primary" @click="ensure">确定</a-button>
            </a-row>-->
          </a-col>
        </a-row>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import { uploadImage, getImg } from '@/api/students'
export default {
  components: {},
  props: {
    // printUrl: {
    //   type: String,
    //   required: true,
    //   default: ''
    // }
  },
  data() {
    return {
      visible: false,
      spinning: false,
      tip: '图片保存中...',
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      uploadParams: {
        tablename: 'Shareholder',
        signname: null
      },
      label1: '设备1',
      label2: '设备2',

      type: '',

      DeviceMain: null,
      DeviceAssist: null,
      VideoMain: null,
      VideoAssist: null,
      videoCapMain: null,
      videoCapAssist: null,

      selRes1: [],
      selResValue1: 0,
      selRes2: [],
      selResValue2: 0,
      resolution1: [],
      resolutionValue1: 0,
      resolution2: [],
      resolutionValue2: 0,

      selScanSize: [{ name: '原始', index: 0 }, { name: '中', index: 1 }, { name: '小', index: 2 }],
      selScanSizeValue: 0,
      //   selRotate: [],
      //   selRotateValue: 0,
      //   selColor: [],
      //   selColorValue: 0,
      //   selDev: [],
      //   selDevValue: 0,
      rotatecrop: false,
      //   delbkcolor: false,
      ScanCtrl: null,
      EThumbnails: null
    }
  },
  watch: {},
  computed: {},
  methods: {
    Left() {
      if (this.VideoMain) {
        this.plugin().Video_RotateLeft(this.VideoMain)
      }
      if (this.VideoAssist) {
        this.plugin().Video_RotateLeft(this.VideoAssist)
      }
    },
    Right() {
      if (this.VideoMain) {
        this.plugin().Video_RotateRight(this.VideoMain)
      }
      if (this.VideoAssist) {
        this.plugin().Video_RotateRight(this.VideoAssist)
      }
    },
    TakePic() {
      var _this = this
      if (_this.VideoMain) {
        var base64 = this.plugin().GetBase64(2, 0)
        let file = this.dataURLtoFile(base64, 'touxiang.jpg')
        this.handPhotoUpload(file)
      }
      if (_this.VideoAssist) {
        var base64 = this.plugin().GetBase64(2, 0)
        let file = this.dataURLtoFile(base64, 'touxiang.jpg')
        this.handPhotoUpload(file)
      }
    },
    show(data1, data2) {
      Object.assign(this, { visible: true, uploadParams: { tablename: data1, signname: data2 } })
      setTimeout(() => {
        this.contentLoad()
      }, 500)
    },
    ensure() {},
    plugin() {
      return document.getElementById('view1')
    },
    MainView() {
      return document.getElementById('view1')
    },
    AssistView() {
      return document.getElementById('view2')
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    contentLoad() {
      this.fun()
    },
    fun() {
      //设备接入和丢失
      //type设备类型， 1 表示视频设备， 2 表示音频设备
      //idx设备索引
      //dbt 1 表示设备到达， 2 表示设备丢失
      var _this = this
      _this.addEvent(_this.plugin(), 'DevChange', function(type, idx, dbt) {
        if (type === 1) {
          //视频设备
          if (dbt === 1) {
            //设备到达
            var deviceType = _this.plugin().Global_GetEloamType(1, idx)
            if (deviceType == 1) {
              //主摄像头
              if (null == _this.DeviceMain) {
                _this.DeviceMain = _this.plugin().Global_CreateDevice(1, idx)
                if (_this.DeviceMain) {
                  _this.label1 = _this.plugin().Device_GetFriendlyName(_this.DeviceMain)
                  _this.selRes1 = []
                  var subType = _this.plugin().Device_GetSubtype(_this.DeviceMain)
                  if (subType & 1) {
                    _this.selRes1.push({ name: 'YUY2', index: 0 })
                  }
                  if (subType & 2) {
                    _this.selRes1.push({ name: 'MJPG', index: 1 })
                  }
                  if (subType & 4) {
                    _this.selRes1.push({ name: 'UYVY', index: 2 })
                  }
                  _this.changesubTypeMain(0)
                  _this.OpenVideoMain(0, 0)
                }
              }
            } else if (2 == deviceType || 3 == deviceType) {
              //辅摄像头
              if (null == _this.DeviceAssist) {
                _this.DeviceAssist = _this.plugin().Global_CreateDevice(1, idx)
                if (_this.DeviceAssist) {
                  _this.label2 = _this.plugin().Device_GetFriendlyName(_this.DeviceAssist)
                  _this.selRes2 = []
                  var subType = plugin().Device_GetSubtype(_this.DeviceAssist)
                  if (subType & 1) {
                    _this.selRes2.push({ name: 'YUY2', index: 0 })
                  }
                  if (subType & 2) {
                    _this.selRes2.push({ name: 'MJPG', index: 1 })
                  }
                  if (subType & 4) {
                    _this.selRes2.push({ name: 'UYVY', index: 2 })
                  }
                  if (0 != (subType & 2) && 0 != (subType & 1)) {
                    //辅摄像头优先采用mjpg模式打开
                    _this.selResValue2 = 1
                  } else {
                    _this.selResValue2 = 0
                  }
                  // initFaceDetectSuccess = plugin().InitFaceDetect()
                  _this.changesubTypeAssist(0)
                  _this.OpenVideoAssist(0, 0)
                }
              }
            }
          } else if (2 == dbt) {
            //设备丢失
            if (_this.DeviceMain) {
              if (_this.plugin().Device_GetIndex(_this.DeviceMain) == idx) {
                _this.CloseVideoMain()
                _this.plugin().Device_Release(_this.DeviceMain)
                _this.DeviceMain = null
                _this.label1 = ''
                _this.selRes1 = []
                _this.resolution1 = []
              }
            }
            if (_this.DeviceAssist) {
              if (_this.plugin().Device_GetIndex(_this.DeviceAssist) == idx) {
                _this.CloseVideoAssist()
                _this.plugin().Device_Release(_this.DeviceAssist)
                _this.DeviceAssist = null
                _this.label2 = ''
                _this.selRes2 = []
                _this.resolution2 = []
              }
            }
          }
        }
      })
    },

    addEvent(obj, name, func) {
      if (obj.attachEvent) {
        obj.attachEvent('on' + name, func)
      } else {
        obj.addEventListener(name, func, false)
      }
    },
    OpenVideo() {
      this.OpenVideoMain(0, 0)
      this.OpenVideoAssist(0, 0)
    },
    CloseVideo() {
      this.CloseVideoMain()
      this.CloseVideoAssist()
    },
    CloseVideoMain() {
      if (this.VideoMain) {
        this.plugin().Video_Release(this.VideoMain)
        this.VideoMain = null
        this.MainView().View_SetText('', 0)
      }
    },
    CloseVideoAssist() {
      if (this.VideoAssist) {
        this.plugin().Video_Release(this.VideoAssist)
        this.VideoAssist = null
        this.AssistView().View_SetText('', 0)
      }
    },
    OpenVideoMain(devData, resoData) {
      this.CloseVideoMain()
      if (!this.DeviceMain) return
      var sSubType = document.getElementById('subType1')
      var sResolution = document.getElementById('selRes1')
      var SelectType = 0
      if (devData == 0) {
        SelectType = 1
      } else if (devData == 1) {
        SelectType = 2
      } else if (devData == 2) {
        SelectType = 4
      }
      this.VideoMain = this.plugin().Device_CreateVideo(this.DeviceMain, resoData, SelectType)
      if (this.VideoMain) {
        this.MainView().View_SelectVideo(this.VideoMain)
        this.MainView().View_SetText('打开视频中，请等待...', 0)
      }
    },
    OpenVideoAssist(devData, resoData) {
      this.CloseVideoAssist()
      if (!this.DeviceAssist) return
      var sSubType = document.getElementById('subType2')
      var sResolution = document.getElementById('selRes2')
      var SelectType = 0
      if (devData == 0) {
        SelectType = 1
      } else if (devData == 1) {
        SelectType = 2
      } else if (devData == 2) {
        SelectType = 4
      }
      this.VideoAssist = plugin().Device_CreateVideo(this.DeviceAssist, resoData, SelectType)
      if (this.VideoAssist) {
        this.AssistView().View_SelectVideo(this.VideoAssist)
        this.AssistView().View_SetText('打开视频中，请等待...', 0)
      }
    },

    changesubTypeMain(data) {
      if (DeviceMain) {
        var SelectType = 0
        if (data == 0) {
          SelectType = 1
        } else if (data == 1) {
          SelectType = 2
        } else if (data == 2) {
          SelectType = 4
        }
        var nResolution = this.plugin().Device_GetResolutionCountEx(DeviceMain, SelectType)
        this.resolution1 = []
        for (var i = 0; i < nResolution; i++) {
          var width = plugin().Device_GetResolutionWidthEx(DeviceMain, SelectType, i)
          var heigth = plugin().Device_GetResolutionHeightEx(DeviceMain, SelectType, i)
          this.resolution1.add({ name: `${String(width)}*${String(heigth)}`, index: i })
        }
      }
    },

    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      // return new File([u8arr], filename, { type: mime }, { uid: `vc-upload-${moment().format('YYYYMMDDHHmmss')}` })

      return new Blob([u8arr], { type: mime })
    },
    afterClose() {
      try {
        this.stop_preview()
      } catch (error) {
        this.visible = false
      }
      this.visible = false
    },
    handPhotoUpload(file) {
      // this.spinning = true
      const { uploadParams } = this
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('您只能上传JPG或PNG!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('必须小于2MB!')
      }
      if (isJpgOrPng && isLt2M) {
        const formData = new FormData()
        formData.append('file', file, 'touxiang.jpg')
        this.uploading = true
        uploadImage(formData, uploadParams).then(res => {
          if (res) {
            this.$message.success('上传成功!')
            const PhotoUrlDb = res
            const PhotoUrl = getImg(`${PhotoUrlDb.Path}${PhotoUrlDb.NewFileName}`)
            this.spinning = false
            this.CloseVideo()
            this.$emit('save', PhotoUrlDb, PhotoUrl, this.uploadParams)
            this.visible = false
          } else {
            this.spinning = false
            this.$message.error('上传失败!')
          }
        })
      }
    },
    Property(url) {
      if (this.DeviceMain) {
        this.plugin().Device_ShowProperty(this.DeviceMain, this.MainView().View_GetObject())
      }
    },
    changeresolution() {
      var num = this.ScanCtrl.GetResolutionCount()
      var x = this.selResValue
      this.ScanCtrl.SetResolution(x)
      this.fun()
    },
    changescansize() {
      var num = this.ScanCtrl.GetScanSizeCount()
      var x = this.selScanSizeValue
      this.ScanCtrl.SetScanSize(x)
      this.fun()
    },
    RotateCrop() {
      this.rotatecrop = !this.rotatecrop
      this.ScanCtrl.SetRotateCrop(this.rotatecrop)
      this.fun()
    }
  },
  created() {},
  mounted() {}
}
</script>
<style lang="less" scoped>
.ant-form-item {
  margin-bottom: 4px;
}
</style>
